package com.xzq.busgstack.server;

import com.xzq.busgstack.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 15:26
 * @Version 1.0.0
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("建立连接....");
        System.out.println("客户端IP:" + sc.localAddress().getHostString());
        System.out.println("客户端端口:" + sc.localAddress().getPort());

        //通知客户端连接成功
        String str = "你好,客户端，咱俩连接没问题了";
        ctx.writeAndFlush(MsgUtil.buildMsg(sc.id().toString(), str));
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("消息类型："+msg.getClass());
        System.out.println("消息内容："+msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接断开.....");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("连接异常: \r\n" + cause.getMessage());
    }
}
